<?php
class IOSS_Order{
	private static $table = 'core_order';
	private static $table_log = 'core_order_log';
	/** 未付款 */
	const PAY_STATE_NOT_PAID = 0;
	/** 已付款 */
	const PAY_STATE_PAID = 1;
	/** 已付款 */
	const PAY_STATE_PAID_CANCEL = -1;
	/** 未充值 */
	const PAY_STATE_NOT_RECHARGED = 0;
	/** 已充值 */
	const PAY_STATE_RECHARGED = 1;
	/** 充值中 */
	const PAY_STATE_RECHARING = 2;
	/** 支付宝付款方式 */
	const PAY_CHANNEL_ALIPAY = 1;
	/** 微信付款方式 */
	const PAY_CHANNEL_WEIXIN = 2;
	/** 银行卡付款方式 */
	const PAY_CHANNEL_BANK = 3;
	
	public static $paymentMethods = Array(self::PAY_CHANNEL_ALIPAY=>'支付宝', self::PAY_CHANNEL_WEIXIN=>'微信',self::PAY_CHANNEL_BANK=>'银联');
	public static $paymentStates = Array(self::PAY_STATE_NOT_PAID=>'通道未确认', self::PAY_STATE_PAID=>'通道已确认',self::PAY_STATE_PAID_CANCEL=>'已取消');
	public static $rechargeStates = Array(self::PAY_STATE_NOT_RECHARGED=>'平台未确认', self::PAY_STATE_RECHARGED=>'平台已确认', self::PAY_STATE_RECHARING=>'平台确认中');

	public static function getPaymentMethod($method=''){
		if($method === ''){
			return self::$paymentMethods;
		}
		return element($method, self::$paymentMethods, '');
	}
	
	public static function getPayState($state=''){
		if($state === ''){
			return self::$paymentStates;
		}
		return element($state, self::$paymentStates, '');
	}
	public static function getRechargeState($state=''){
		if($state === ''){
			return self::$rechargeStates;
		}
		return element($state, self::$rechargeStates, '');
	}

	/**
	 * 存款记录请求
	 * @param string $user_id
	 * @param int $offset
	 */
	public static function getOrderList($user_id, $last_id){
		$db = IOSS_DB::getInstance();
		$db->select(array('id','amount as price','pay_status as status', 'FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%S") as time'));
		$db->from(self::$table);
		$db->where('user_id',$user_id);
		if($last_id){
			$db->where('id<',$last_id);
		}
		$db->order_by('id','DESC');
		$db->limit('8');
		$query = $db->get();
		return $query->result();
	}

	/**
	 * 创建订单
	 * @param string $user_id
	 * @param int $amount
	 * @param string $pay_channel
	 * @param string $transfer_platform
	 * @return boolean|IOSS_Order
	 */
	public static function create($user_id, $amount, $pay_channel, $transfer_platform){
		$db = IOSS_DB::getInstance();
		$time = time();
		$o['user_id'] = $user_id;
		$o['amount'] = $amount;
		$o['pay_status'] = self::PAY_STATE_NOT_PAID;
		$o['pay_time'] = 0;
		$o['pay_channel'] = $pay_channel;
		$o['pay_transaction'] = '';
		$o['transfer_platform'] = $transfer_platform;
		$o['transfer_status'] = self::PAY_STATE_NOT_RECHARGED;
		$o['transfer_time'] = 0;
		$o['create_time'] = $time;
		$o['update_time'] = $time;
		$try_times = 0;
		do{
			if($try_times > 10){
				return  false; //重试次数太多，创建订单失败
			}
			$try_times ++;
			$o['no'] = date('ymdHis') . rand(1000, 9999);
			$unique = $db->get_where(self::$table, array('no' => $o['no']))->num_rows() === 0;
		}while($unique === false);
	
		if($db->insert(self::$table, $o)){
			$o['id'] =  $db->insert_id();
			return new self($o);
		}else{
			return false;
		}
	}
	
	
	/**
	 * 获取订单
	 * @param int $id
	 * @return Ambigous <NULL, IOSS_Order>
	 */
	public static function getById($id){
		$db = IOSS_DB::getInstance();
		$row = $db->where('id', $id)->get(self::$table)->row_array();
		return ($row == null) ? null : (new self($row));
	}
	
	/**
	 * 根据订单号获取订单
	 * @param string $no
	 * @return Ambigous <NULL, IOSS_Order>
	 */
	public static function getByNo($no){
		$db = IOSS_DB::getInstance();
		$row = $db->where('no', $no)->get(self::$table)->row_array();
		return ($row == null) ? null : (new self($row));
	}
	/**
	 * 获取订单列表
	 * @param array $where
	 * @param number $limit
	 * @return array<IOSS_Order>
	 */
	public static function getList($where, $limit = 10){
		$db = IOSS_DB::getInstance();
		$db->where($where);
		$db->order_by('id', 'desc');
		if($limit){
			$db->limit($limit);
		}
		$rows = $db->get(self::$table)->result_array();
		return array_map(function ($row){
			return new self($row);
		}, $rows);
	}
	
	
	private $order;
	
	private function __construct($row){
		$this->order = $row;
	}
	
	public function __get($key){
		return $this->order[$key];
	}
	
	/**
	 * 完成支付
	 * @param string $note
	 * @param string $transaction
	 * @return boolen
	 */
	public function pay($note = '', $transaction = ''){
		$db = IOSS_DB::getInstance();
		$time = time();
		$update['pay_status'] = self::PAY_STATE_PAID;
		$update['pay_time'] = $time;
		$update['pay_transaction'] = $transaction;
		$update['update_time'] = $time;
		$success = $db->where('id', $this->order['id'])->update(self::$table, $update) && ($db->affected_rows() >= 1);
		if($success ){
			$this->order = array_merge($this->order, $update);
			$this->log($note);
		}
		return $success;
	}
	
	/**
	 * 完成游戏内充值
	 * @param string $note
	 * @return boolen
	 */
	public function transfer($note = ''){

		$user = IOSS_User::getById($this->order['user_id']);
		$billno = date('ymdHis') . rand(1000,9999);
		if (!$this->order['pay_status']) {
			return false;
		}
		// 预转账
		if(!IOSS_AGApi::agin_prepare_transfer_credit($user->account, $user->game_key, $billno, 'IN', $this->order['amount'], $prepare_error_message)){
			return false; // 预转账失败
		}
		// 转账确认
		if (!IOSS_AGApi::agin_confirm_transfer_credit($user->account, $user->game_key, $billno, 'IN', $this->order['amount'], $confirm_error_message)){ 
			if ($confirm_error_message['Type'] === 'network_error') {
				if (!IOSS_AGApi::agin_query_transfer_status($billno, $query_error_message)) {
					return false;
				}	
			}else{
				return false;
			}
		}

		$db = IOSS_DB::getInstance();
		$time = time();
		$update['transfer_status'] = self::PAY_STATE_RECHARGED;
		$update['transfer_time'] = $time;
		$update['update_time'] = $time;
		$success = $db->where('id', $this->order['id'])->update(self::$table, $update)  && ($db->affected_rows() >= 1);
		if($success){
			$this->order = array_merge($this->order, $update);
			$this->log($note);
		}
		return $success;
	}
	
	/**
	 * 添加订单日志
	 * @param string $note
	 */
	public function log($note){
		$db = IOSS_DB::getInstance();
		$log['order_id'] = $this->order['id'];
		$log['pay_status'] =  $this->order['pay_status'];
		$log['transfer_status'] = $this->order['transfer_status'];
		$log['admin_id'] = 0;
		$log['admin_account'] = 'systme';
		$log['admin_name'] = '系统';
		$log['note'] = $note;
		$log['create_time'] = time();
		$db->insert(self::$table_log, $log);
	}
	
}